/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.cmd;

import com.google.common.base.Strings;
import com.je.bpm.common.operation.OperatorEnum;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.config.CounterSignPassTypeEnum;
import com.je.bpm.core.model.config.CustomEvent;
import com.je.bpm.core.model.task.KaiteCounterSignUserTask;
import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.delegate.DelegateExecution;
import com.je.bpm.engine.impl.bpmn.behavior.MultiInstanceActivityBehavior;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.ExecutionEntity;
import com.je.bpm.engine.impl.persistence.entity.TaskEntity;
import com.je.bpm.engine.impl.util.ProcessDefinitionUtil;

import java.util.List;
import java.util.Map;

/**
 * 更改负责人任务命令
 */
public class CountersignedChangePersonCmd extends AbstractCompleteTaskCmd {

    private String taskId;

    private String assignee;

    public CountersignedChangePersonCmd(String assignee, String prod, Map<String, Object> bean, String taskId) {
        super(taskId, prod, bean);
        this.taskId = taskId;
        this.assignee = assignee;
    }

    public String getTaskId() {
        return taskId;
    }

    public void setTaskId(String taskId) {
        this.taskId = taskId;
    }

    public String getAssignee() {
        return assignee;
    }

    public void setAssignee(String assignee) {
        this.assignee = assignee;
    }

    @Override
    protected Void execute(CommandContext commandContext, TaskEntity task) {
        // 根据执行实例ID获取当前执行实例
        String executionId = task.getExecutionId();
        BpmnModel bpmnModel = ProcessDefinitionUtil.getBpmnModel(task.getProcessDefinitionId());
        KaiteCounterSignUserTask miActivityElement = getCurrentUserTask(task, bpmnModel);

        ExecutionEntity rootExecution = (ExecutionEntity) getMultiInstanceRootExecution(task.getExecution());

        isMuTask(miActivityElement, executionId, rootExecution);

        rootExecution.setVariable(MultiInstanceActivityBehavior.PASS_PRINCIPAL, assignee);
        rootExecution.setVariable(MultiInstanceActivityBehavior.PRINCIPAL_OPINION, "");

        for (DelegateExecution execution : rootExecution.getExecutions()) {
            ExecutionEntity executionEntity = (ExecutionEntity) execution;
            List<TaskEntity> list = executionEntity.getTasks();
            for (TaskEntity task1 : list) {
                task1.setVariableLocal(MultiInstanceActivityBehavior.PASS_PRINCIPAL, assignee);
            }
        }

        executeAfterHandler(bpmnModel, task, CustomEvent.CustomEventEnum.TASK_CHANGE_PERSON, "更换负责人", OperatorEnum.TASK_CHANGE_ASSIGNEE_OPERATOR);

        return null;
    }

    private KaiteCounterSignUserTask getCurrentUserTask(TaskEntity task, BpmnModel bpmnModel) {
        KaiteCounterSignUserTask miActivityElement = (KaiteCounterSignUserTask) bpmnModel.getFlowElement(task.getTaskDefinitionKey());
        return miActivityElement;
    }

    private void isMuTask(KaiteCounterSignUserTask miActivityElement, String executionId, ExecutionEntity miExecution) {
        List<String> users = getListVariable(miExecution, MultiInstanceActivityBehavior.PROCESSING_USERS_INFO);

        if (!users.contains(assignee)) {
            throw new ActivitiException(String.format("%s:当前处理人不存在，无法更换负责人！", assignee));
        }

        if (miActivityElement.getLoopCharacteristics() == null) {
            throw new ActivitiException("不是多实例节点 " + executionId);
        }

        if (!miActivityElement.getCounterSignConfig().getCounterSignPassType().toString().equals(CounterSignPassTypeEnum.PASS_PRINCIPAL.toString())) {
            throw new ActivitiException("不是负责人会签无法更换负责人");
        }
        //负责人意见
        String principalOpinion = getStringVariable(miExecution, MultiInstanceActivityBehavior.PRINCIPAL_OPINION);
        if (!Strings.isNullOrEmpty(principalOpinion)) {
            throw new ActivitiException("负责人已审批，无法更换！");
        }

    }

    protected Integer getLoopVariable(DelegateExecution execution, String variableName) {
        Object value = execution.getVariableLocal(variableName);
        DelegateExecution parent = execution.getParent();
        while (value == null && parent != null) {
            value = parent.getVariableLocal(variableName);
            parent = parent.getParent();
        }
        return (Integer) (value != null ? value : 0);
    }

    protected String getStringVariable(DelegateExecution execution, String variableName) {
        Object value = execution.getVariableLocal(variableName);
        DelegateExecution parent = execution.getParent();
        while (value == null && parent != null) {
            value = parent.getVariableLocal(variableName);
            parent = parent.getParent();
        }
        return (String) (value != null ? value : "");
    }

    protected DelegateExecution getMultiInstanceRootExecution(DelegateExecution executionEntity) {
        DelegateExecution multiInstanceRootExecution = null;
        DelegateExecution currentExecution = executionEntity;
        while (currentExecution != null && multiInstanceRootExecution == null && currentExecution.getParent() != null) {
            if (currentExecution.isMultiInstanceRoot()) {
                multiInstanceRootExecution = currentExecution;
            } else {
                currentExecution = currentExecution.getParent();
            }
        }
        return multiInstanceRootExecution;
    }

}
